let msgStorage = require("../msgstorage");

var onfire = require('../../../utils/event')

let { produce } = require("../../../utils/immer");




let LIST_STATUS = {
	SHORT: "scroll_view_change",
	NORMAL: "scroll_view"
};



var app = getApp();
Component({
	properties: {
		username: {
			type: Object,
			value: {},
		},
	},
	data: {
		view: LIST_STATUS.NORMAL,
		toView: "",
		chatMsg: [],
        userRole:1, //0:c端 1:b端
		__visibility__: false,
	},
	methods: {
		normalScroll(){
			this.setData({
				view: LIST_STATUS.NORMAL
			});
		},
    //立即推送
    pushImmediately(e) {
      wx.showModal({
        title: '确认推送给客户',
        content: '含本次还可以向客户推送3次',
        confirmText:"立即推送",
        confirmColor:"#1f90e6",
        success(res) {
          if (res.confirm) {
            let index = e.currentTarget.id;
           
            wx.showToast({
              title: '推送成功',
              icon: 'success',
              duration: 2000,
              success:function(){
                wx.setStorageSync("noticeIndex", index);
                onfire.fire('clientPush');
              }
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    },
		shortScroll(){
			this.setData({
				view: LIST_STATUS.SHORT
			});
		},

		onTap(){
			this.triggerEvent("msglistTap", null, { bubbles: true });
		},

		previewImage(event){
			var url = event.target.dataset.url;
			wx.previewImage({
				urls: [url]		// 需要预览的图片 http 链接列表
			});
		},
        enter: function (event) {
            wx.navigateTo({
                url: "/pages/chat/chat"
            });
        },

    readMsg(){

    },
		renderMsg(renderableMsg, type, curChatMsg, sessionKey){
			var historyChatMsgs = wx.getStorageSync("rendered_" + sessionKey) || [];
			historyChatMsgs = historyChatMsgs.concat(curChatMsg);
			//if(!historyChatMsgs.length) return;
            wx.setStorageSync("rendered_" + sessionKey, historyChatMsgs);
            this.setData({
                chatMsg: historyChatMsgs,
                // // 跳到最后一条
               // toView: historyChatMsgs[historyChatMsgs.length - 1].mid,
            });
            let _this = this
            //服务器回执
             onfire.one('serverReceiptt', function () {
                console.log("serverReceiptt")
                //onfire.un('serverReceiptt');
                setTimeout(function(){
                  //onfire.un('serverReceiptt');
                  var historyChatMsgs = wx.getStorageSync(wx.getStorageSync("currentChat")) || [];
                  if (historyChatMsgs.length == 1) {
                    historyChatMsgs[0].msgState = 1
                  }
                  else {
                    historyChatMsgs[parseInt(historyChatMsgs.length) - 1].msgState = 1
                  }
                  
                  _this.setData({
                    chatMsg: historyChatMsgs
                  });
                  wx.setStorageSync(wx.getStorageSync("currentChat"), historyChatMsgs);
                },600)
                
            });
          //客户端回执
           onfire.one('clientReceiptt', function () {
            console.log("clientReceiptt")
            setTimeout(function () {
              var historyChatMsgs = wx.getStorageSync(wx.getStorageSync("currentChat")) || [];
              var history = produce(historyChatMsgs, draft => {
                historyChatMsgs.forEach((item, index) => {
                  draft[index].msgState = 2
                })
              })
              console.log(history)
              _this.setData({
                chatMsg: history
              });
              wx.setStorageSync(wx.getStorageSync("currentChat"), history);
              
            }, 600)
          });
        //推送状态回执
        onfire.one('clientPush', function () {
          console.log("clientPush")
          setTimeout(function () {
            var historyChatMsgs = wx.getStorageSync(wx.getStorageSync("currentChat")) || [];
            let index = wx.getStorageSync("noticeIndex")
            if (index==0){
              historyChatMsgs[0].notice = 1
            }
            else
            {
              historyChatMsgs[wx.getStorageSync("noticeIndex")].notice = 1
            }
            _this.setData({
              chatMsg: historyChatMsgs
            });
            wx.setStorageSync(wx.getStorageSync("currentChat"), historyChatMsgs);
          }, 600)
        });
           
			wx.setStorageSync(sessionKey, null);
		},
	},

	// lifetimes
	created(){},
	attached(){
		this.__visibility__ = true;
	},
	moved(){},
	detached(){
		this.__visibility__ = false;
	},
	ready(){
     app.globalData.chat=this
		let me = this;
		let username = this.data.username;
		let myUsername = wx.getStorageSync("myUsername");
		let sessionKey =username.your + myUsername;
		let chatMsg = wx.getStorageSync(sessionKey) || [];
        let currentChat = "rendered_" + sessionKey
		this.renderMsg(null, null, chatMsg, sessionKey);
        wx.setStorageSync("currentChat", currentChat);
		msgStorage.on("newChatMsg", function(renderableMsg, type, curChatMsg){
			if(!me.__visibility__) return;
			// 判断是否属于当前会话
			if(username.groupId){
				// 群消息的 to 是 id，from 是 name
				if(renderableMsg.info.from == username.groupId || renderableMsg.info.to == username.groupId){
					me.renderMsg(renderableMsg, type, curChatMsg, sessionKey);
				}
			}
			else if(renderableMsg.info.from == username.your || renderableMsg.info.to == username.your){
				me.renderMsg(renderableMsg, type, curChatMsg, sessionKey);
			}
		});
      
  

        
	},
   
   
});
